package com.atguigu.gulimall.seckill.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 自定义流控响应
 */
@Configuration
public class SeckillSentinelConfig {
    /**
     * 2.2.0以前的版本实现的是 WebCallbackManager，2.2.0以后的版本实现的是 BlockExceptionHandler 接口，重写 handle() 方法
     */
    public SeckillSentinelConfig() {
        WebCallbackManager.setUrlBlockHandler((request, response, ex) -> {    //TOO_MANY_REQUESTS_EXCEPTION(10003, "请求流量多大"
            R error = R.error(BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getCode(), BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getMsg());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSON.toJSONString(error));
        });
    }

//    /**
//     * 2.2.0以后的版本实现的是 BlockExceptionHandler；以前的版本实现的是 WebCallbackManager
//     */
//    @Override
//    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
//        R error = R.error(BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getCode(), BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getMsg());
//        httpServletResponse.setCharacterEncoding("UTF-8");
//        httpServletResponse.setContentType("application/json");
//        httpServletResponse.getWriter().write(JSON.toJSONString(error));
//    }
}
